<?php
declare(strict_types=1);

namespace SixShop\MakerBundle\Generator;

use Symfony\Component\Console\Style\SymfonyStyle;

class RouteUpdater
{
    /**
     * Update route files with new resource routes
     */
    public function updateRoutes(
        string $tableName, 
        string $tableComment, 
        array $extensionInfo, 
        string $targetPath, 
        SymfonyStyle $io
    ): bool {
        try {
            $success = true;
            
            // Update API routes
            $success = $this->updateApiRoutes($tableName, $tableComment, $extensionInfo, $targetPath, $io) && $success;
            
            // Update Admin routes
            $success = $this->updateAdminRoutes($tableName, $tableComment, $extensionInfo, $targetPath, $io) && $success;
            
            return $success;
            
        } catch (\Exception $e) {
            $io->error('更新路由文件时发生错误: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Update API routes file
     */
    private function updateApiRoutes(
        string $tableName, 
        string $tableComment, 
        array $extensionInfo, 
        string $targetPath, 
        SymfonyStyle $io
    ): bool {
        try {
            $routeFile = $targetPath . '/route/api.php';
            
            if (!file_exists($routeFile)) {
                $io->warning("API路由文件不存在: {$routeFile}");
                return true; // Not an error, just skip
            }
            
            $controllerName = $this->generateControllerName($tableName);
            $resourceName = $this->generateResourceName($tableName);
            $namespace = rtrim($extensionInfo['namespace'], '\\');
            
            // Generate route code
            $routeCode = $this->generateApiRouteCode(
                $controllerName, 
                $resourceName, 
                $namespace, 
                $tableComment
            );
            
            // Read current file content
            $currentContent = file_get_contents($routeFile);
            
            // Check if routes already exist
            if (strpos($currentContent, "'{$resourceName}'") !== false) {
                $io->text("API路由已存在，跳过: {$resourceName}");
                return true;
            }
            
            // Append new routes
            $newContent = rtrim($currentContent) . "\n\n" . $routeCode;
            
            // Write updated content
            if (file_put_contents($routeFile, $newContent) !== false) {
                $io->text("✓ 更新API路由文件: route/api.php");
                return true;
            } else {
                $io->error("✗ 无法写入API路由文件");
                return false;
            }
            
        } catch (\Exception $e) {
            $io->error('更新API路由时发生错误: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Update Admin routes file
     */
    private function updateAdminRoutes(
        string $tableName, 
        string $tableComment, 
        array $extensionInfo, 
        string $targetPath, 
        SymfonyStyle $io
    ): bool {
        try {
            $routeFile = $targetPath . '/route/admin.php';
            
            if (!file_exists($routeFile)) {
                $io->warning("Admin路由文件不存在: {$routeFile}");
                return true; // Not an error, just skip
            }
            
            $controllerName = $this->generateControllerName($tableName);
            $resourceName = $this->generateResourceName($tableName);
            $namespace = rtrim($extensionInfo['namespace'], '\\');
            
            // Generate route code
            $routeCode = $this->generateAdminRouteCode(
                $controllerName, 
                $resourceName, 
                $namespace, 
                $tableComment
            );
            
            // Read current file content
            $currentContent = file_get_contents($routeFile);
            
            // Check if routes already exist
            if (strpos($currentContent, "'{$resourceName}'") !== false) {
                $io->text("Admin路由已存在，跳过: {$resourceName}");
                return true;
            }
            
            // Append new routes
            $newContent = rtrim($currentContent) . "\n\n" . $routeCode;
            
            // Write updated content
            if (file_put_contents($routeFile, $newContent) !== false) {
                $io->text("✓ 更新Admin路由文件: route/admin.php");
                return true;
            } else {
                $io->error("✗ 无法写入Admin路由文件");
                return false;
            }
            
        } catch (\Exception $e) {
            $io->error('更新Admin路由时发生错误: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Generate API route code
     */
    private function generateApiRouteCode(
        string $controllerName, 
        string $resourceName, 
        string $namespace, 
        string $tableComment
    ): string {
        $controllerClass = "{$namespace}\\Controller\\Api\\{$controllerName}";
        
        $code = "// {$tableComment}相关路由\n";
        $code .= "Route::resource('{$resourceName}', {$controllerClass}::class);";
        
        return $code;
    }

    /**
     * Generate Admin route code
     */
    private function generateAdminRouteCode(
        string $controllerName, 
        string $resourceName, 
        string $namespace, 
        string $tableComment
    ): string {
        $controllerClass = "{$namespace}\\Controller\\Admin\\{$controllerName}";
        
        $code = "// {$tableComment}管理路由\n";
        $code .= "Route::resource('{$resourceName}', {$controllerClass}::class);";
        
        return $code;
    }

    /**
     * Generate controller class name from table name
     */
    private function generateControllerName(string $tableName): string
    {
        // Remove common prefixes
        $tableName = preg_replace('/^(tbl_|tb_|t_)/', '', $tableName);
        
        // Convert to PascalCase and make singular
        $parts = explode('_', $tableName);
        $parts = array_map('ucfirst', $parts);
        $name = implode('', $parts);
        
        // Make singular (simple rules)
        if (str_ends_with($name, 's') && !str_ends_with($name, 'ss')) {
            $name = substr($name, 0, -1);
        }
        
        return $name . 'Controller';
    }

    /**
     * Generate resource name from table name (for routes)
     */
    private function generateResourceName(string $tableName): string
    {
        // Remove common prefixes
        $tableName = preg_replace('/^(tbl_|tb_|t_)/', '', $tableName);
        
        // Keep underscore format for URLs
        return $tableName;
    }
}